package com.le.enhance.class4;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个数组,其中包含[奇数,偶素]返回[奇数,偶数:个数相等]的最长子数组的长度
 * 思路:
 * 1. 转化数组arr,奇数为-1,偶数为1
 * 2. 求在arr中，累加和等于0的最长子数组的长度
 */

public class Code_05_1_LongestSumSubArrayLength {

    public static int getMaxLength(int[] arr){
        return maxLength(transfer(arr),0);
    }

    public static int maxLength(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int sum = 0;
        int len = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            if (map.containsKey(sum - num)) {
                len = Math.max(i - map.get(sum - num), len);
            }
            if (!map.containsKey(sum)) {
                map.put(sum, i);
            }
        }
        return len;
    }


    public static int[] transfer(int[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] % 2 == 0 ? 1 : -1;
        }
        System.out.println(Arrays.toString(arr));
        return arr;
    }

    public static int[] generateArray(int size) {
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = (int) (Math.random() * 11) - 5;
        }
        return arr;
    }

    @Test
    public void test() {
        int[] array = generateArray(5);
        System.out.println(Arrays.toString(array));
        System.out.println(getMaxLength(array));

    }
}
